#include "Mutex.hpp"
#include <pthread.h>
#include <vector>
#include <unistd.h>

using namespace MutexModlue;

int ticket = 1000;

// pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

struct ThreadData
{
    std::string _name;
    Mutex *_mutex;
    ThreadData(const char *name, Mutex &mutex)
        : _name(name), _mutex(&mutex)
    {
    }
};

void *routine(void *ags)
{
    ThreadData *td = static_cast<ThreadData *>(ags);
    while (true)
    {
        // pthread_mutex_lock(&mutex);
        // td->_mutex->Lock();
        LockGuard lg(*td->_mutex);
        if (ticket > 0)
        {
            usleep(10000);
            std::cout << td->_name << ":" << ticket << std::endl;
            ticket--;
            // pthread_mutex_unlock(&mutex);
            // td->_mutex->Unlock();
        }
        else
        {
            // pthread_mutex_unlock(&mutex);
            // td->_mutex->Unlock();
            break;
        }
    }
    return nullptr;
}

int main()
{
    std::vector<pthread_t> threads;
    pthread_t tid;

    Mutex lock;

    for (int i = 0; i < 5; i++)
    {
        char name[64];
        snprintf(name, 64, "thread-%d", i);
        ThreadData *td = new ThreadData(name, lock);
        pthread_create(&tid, nullptr, routine, (void *)td);
        threads.emplace_back(tid);
    }

    for (auto &thread : threads)
    {
        pthread_join(thread, nullptr);
    }

    // delete ...

    return 0;
}